import path from "path";
import { app, BrowserWindow } from "electron";
import "./ipc";

process.env.DIST_ELECTRON = path.join(__dirname, "..");
process.env.DIST = path.join(process.env.DIST_ELECTRON, "../dist");
process.env.PUBLIC = process.env.VITE_DEV_SERVER_URL
  ? path.join(process.env.DIST_ELECTRON, "../public")
  : process.env.DIST;
let win: BrowserWindow | null;
// Here, you can also use other preload
const preload = path.join(__dirname, "../preload/index.js");
const url = process.env.VITE_DEV_SERVER_URL;
const indexHtml = path.join(process.env.DIST, "index.html");

function createWindow() {
  setProtocolClient();
  win = new BrowserWindow({
    icon: path.join(process.env.PUBLIC, "favicon.ico"),
    webPreferences: {
      // contextIsolation: false,
      // nodeIntegration: true,
      // nodeIntegrationInWorker: true,
      // webSecurity: false,
      preload
    }
  });

  // Test active push message to Renderer-process.
  win.webContents.on("did-finish-load", () => {
    win?.webContents.send("main-process-message", new Date().toLocaleString());
  });

  if (process.env.VITE_DEV_SERVER_URL) {
    win.loadURL(`${url}#/examples/directive`);
    win.webContents.openDevTools({ mode: "right", activate: true });
  } else {
    win.loadFile(indexHtml, {
      hash: "/examples/directive"
    });
  }
}

app.on("window-all-closed", () => {
  win = null;
});

function setProtocolClient() {
  if (app.isPackaged) {
    app.setAsDefaultProtocolClient("scheme");
  } else {
    app.setAsDefaultProtocolClient("scheme", process.execPath, [
      path.resolve(process.argv[1])
    ]);
  }
}
app.whenReady().then(createWindow);
